import './index.css';
import 'utils/js/px2rem.mobile';
import ChatWall from 'components/chat-wall';
import ChatFoot from 'components/chat-foot';
import { getParamFromSearch } from 'utils/js/tools';
import { apiRoot, wsRoot } from 'utils/js/config';
import AIChatSocket from 'utils/js/aichat-socket';
import $ from 'jquery';
import layer from 'utils/js/layer-mobile';

var queryParam = getParamFromSearch();
var userInfo = JSON.parse(window.localStorage.getItem('aichat_user_info'));
var chatWall = new ChatWall('#main');
var chatFoot = new ChatFoot('#foot');

Promise.all([
  new Promise(function (resolve, reject) {
    new AIChatSocket({
      url: `${wsRoot}ws/chat/${queryParam.rid}/${userInfo.userid}`,
      onopen: function () {
        resolve(this);
      },
      onerror: reject,
      onclose: reject,
    });
  }),
  new Promise(function (resolve, reject) {
    $.ajax({
      type: 'get',
      url: `${apiRoot}v1/record/${queryParam.rid}`,
      dataType: 'json',
      success: function (res) {
        if (res.code == 200) {
          resolve(res.data)
        } else {
          reject(res.error)
        }
      },
      error: reject,
    });
  }),
]).then(function (arr) {
  $('#loading').fadeOut();

  var ws = arr[0]; // WebSocket实例
  var chatData = arr[1]; // 初始聊天消息

  // socket消息处理
  ws.opt.onmessage = function (d, e) {
    switch (d.type) {
      case 'chat':
        chatWall.add(d.data);
        break;
      default:
        console.log(d);
    }
  };

  // 发送消息处理
  chatFoot.on('send', function (data) {
    if (data.words || data.imgs.length) {
      ws.send({ type: 'chat', data: data });
    } else {
      layer.msg('聊天消息不能为空')
    }
  });

  // 装载初始聊天信息
  chatWall.prepend(chatData);
}).catch(function (e) {
  console.error(e);
});

